<template>
  <div class="wangEditor-container">
    <div :id="id" :style="{ 'width': width + 'px' }" :class="menus.length <= 0 ? 'wangEditor_no_menus' : ''"></div>
    <!-- <Toolbar
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            v-model="value"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
        /> -->
  </div>
</template>

<script>
import E from "wangeditor";
import { BASEURL, CREATESIGN } from "@/http/interface";
import axios from "@/http/api";
import { COMMONFILEUPLOAD } from "@/http/system";
import * as imageConversion from 'image-conversion';
import { COMPRESS_RATE } from '@/common/constants'
// import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
  name: "WangEditor",
  // components:{
  //   Editor,
  //   Toolbar
  // },
  props: {
    id: {
      type: String,
      default: function () {
        return (
          "wang-editor" + +new Date() + ((Math.random() * 1000).toFixed(0) + "")
        );
      },
    },
    value: {
      type: String,
      default: "",
    },
    toolbar: {
      type: Array,
      required: false,
      default() {
        return [];
      },
    },
    menubar: {
      type: String,
      default: "file edit insert view format table",
    },
    height: {
      type: [Number, String],
      required: false,
      default: 300,
    },
    width: {
      type: [Number, String],
      required: false,
      default: "auto",
    },
    url: {
      type: String,
      default: COMMONFILEUPLOAD,
    },
    placeholder: {
      type: String,
      default: "请输入",
    },
    menus: {
      type: Array,
      default: function () {
        return ['head',
          'bold',
          'fontSize',
          'fontName',
          'italic',
          'underline',
          'strikeThrough',
          'indent',
          'lineHeight',
          'foreColor',
          'backColor',
          'link',
          'list',
          'todo',
          'justify',
          'quote',
          'emoticon',
          'image',
          'video',
          'table',
          'code',
          'splitLine',
          'undo',
          'redo',]
      },
      showFullScreen: {
        type: Boolean,
        default: true
      }
    }
  },
  data() {
    return {
      fileParams: {},
      editor: '',
      mode: 'default', // or 'simple'
      editorConfig: { placeholder: '请输入内容...' },
      toolbarConfig:{}
    };
  },
  computed: {},
  watch: {
    // value: {
    //   handler: function (n, o) {
    //     if (this.editor) {
    //       this.editor.txt.html(n);
    //     }
    //   },
    //   immediate: true
    // }
  },
  mounted() {
    this.init();
  },
  methods: {
    /** 初始化编辑器 */
    init() {
      let _this = this;
      const editor = new E("#" + _this.id);
      editor.config.height = this.height
      editor.config.menus = this.menus
      editor.config.showFullScreen = this.showFullScreen
      editor.config.uploadImgServer = _this.url;
      editor.config.placeholder = _this.placeholder;
      editor.config.zIndex = 500
      editor.config.onchange = function (newHtml) {
        _this.$emit("change", newHtml);
        _this.$emit("input", newHtml);
      };

      editor.config.customUploadImg = function (resultFiles, insertImgFn) {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法

        // 上传图片，返回结果，将图片插入到编辑器中
        //insertImgFn(imgUrl);
        console.log(insertImgFn);
        let o = resultFiles[0];
        _this.fileUpload(o, insertImgFn);
      };

      editor.config.uploadImgParams = _this.fileParams;
      editor.create();
      this.editor = editor
      setTimeout(function(){
        if (_this.value) {
        editor.txt.html(_this.value);
      }
      },300)
      
    },
    /** 监听文件上传之前 */
    async fileUpload(file, callBack) {
      let _this = this;
      let headers = { "Content-Type": "multipart/form-data" };
      let o = new FormData();

      let resFiles = await imageConversion.compress(file, COMPRESS_RATE);
      let newFile = new File([resFiles], file.name, { type: resFiles.type, lastModified: Date.now() })
      o.append("file", newFile);
      headers.Authorization = sessionStorage.getItem("token");
      console.log(file);
      let res = await axios({
        method: "post",
        withCredentials: false,
        url: _this.url,
        data: o,
        headers: { "Content-Type": "multipart/form-data" },
      })

      let url = BASEURL + res.data;
      callBack(url);

      // axios({
      //   method: "post",
      //   withCredentials: false,
      //   url: _this.url,
      //   data: o,
      //   headers: { "Content-Type": "multipart/form-data" },
      // }).then((res) => {
      //   let url = BASEURL + res.data;
      //   callBack(url);
      // });
    },
  },
};
</script>

<style lang="scss">
.w-e-toolbar p,
.w-e-text-container p,
.w-e-menu-panel p {
  font-size: 14px !important;
  margin: 2px 0;
}
</style>
<style lang="scss" scoped>
.wangEditor_no_menus {
  ::v-deep .w-e-toolbar {
    display: none;
  }

  ::v-deep .w-e-text-container {
    border: 1px solid #c9d8db !important;
    border-radius: 4px;
  }
}
</style>
